package com.franklin.validation.core.webflux.handler;
import com.franklin.validation.core.RequestParamRuleFactory;
import com.franklin.validation.core.config.ValidationConfig;
import com.franklin.validation.core.constants.Constants;
import com.franklin.validation.core.exception.ParamCheckException;
import com.franklin.validation.core.response.JsonResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * Description :
 * Create By: Franklin
 * Date : 2020/6/11 14:27
 */
@RestControllerAdvice
public class ParamCheckExceptionHandler {

    @Autowired
    private RequestParamRuleFactory factory;
    @Autowired
    private ValidationConfig validationConfig;

    @ExceptionHandler(ParamCheckException.class)
    public Object paramCheckException(ParamCheckException ex){
        String msg;
        String message = ex.getMessage();
        if (message.startsWith(Constants.MESSAGE)){
            msg = message.split(":")[1];
        }else {
            msg = String.format(this.validationConfig.getMessage(),message);
        }
        return this.factory.getResponse(this.validationConfig.getCode() + Constants.COMMA + msg,ex.getResultType());
    }
}
